import React, {useState, useEffect, useRef} from 'react';
import {
  View,
  Text,
  FlatList,
  Image,
  TouchableOpacity,
  StyleSheet,
} from 'react-native';
import theme from '../utils/theme';
import Toast from 'react-native-toast-message';
import {showToast} from '../utils/toastUtils';
import { normalize, screenHeight } from "../utils/commonUtils";
import API from '../Network/Api';
import { CustomText } from "../customview/CustomText";

const WholesaleScreen = ({navigation, route}) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [products, setProducts] = useState([]);
  const [purchasedItems, setPurchasedItems] = useState([]);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [hasMore, setHasMore] = useState(false);
  const flatListRef = useRef(null);

  useEffect(() => {
    fetchProducts();
  }, []);

  const fetchProducts = async () => {
    try {
      const response = await API.pointsGoodsReq(currentPage, '20');
      if (response.resultCode === '1') {
        const fetchedData = response.data.baseGoods.rows;
        const data = fetchedData.map((item, index) => {
          let priceStr =
            item.spjg || Math.floor(Math.random() * 3000).toString();
          let priceNum = parseFloat(priceStr);
          let priceFixed = priceNum.toFixed(0);
          let finalPrice = parseFloat(priceFixed);
          return {
            id: item.id || index + 1,
            name: item.spbt || `商品 ${index + 1}`,
            price: priceFixed,
            quantity: finalPrice / theme.app.unitPrice,
            image: theme.app.productImg,
          };
        });
        const total = response.data.baseGoods.total;
        setHasMore(products.length + data.length < total);
        if (currentPage === 1) {
          setProducts(data);
        } else {
          setProducts([...products, ...data]);
        }
      } else {
        showToast({
          text2: '网络异常',
        });
      }
    } catch (error) {
      showToast({
        text2: '获取商品数据操作异常',
      });
    } finally {
      setIsRefreshing(false);
    }
  };

  const handleItemPress = item => {
    navigation.navigate('ProductDetailPage', {
      productItem: item,
    });
  };

  const renderProduct = ({item}) => (
    <TouchableOpacity style={styles.productContainer} onPress={() => handleItemPress(item)}>
      <Image source={item.image} style={styles.productImage} />
      <CustomText style={styles.nameStyle}>{item.name}</CustomText>
      <View style={styles.pointBgStyle}>
        <CustomText style={styles.pointStyle}>{item.price}积分兑换</CustomText>
      </View>
    </TouchableOpacity>
  );

  const EmptyListComponent = () => (
    <View style={styles.emptyListContainer}>
      <CustomText style={styles.emptyListText}>暂无积分商品</CustomText>
    </View>
  );

  const onRefresh = () => {
    setIsRefreshing(true);
    setCurrentPage(1);
    fetchProducts();
  };

  const onEndReached = () => {
    if (hasMore) {
      const nextPage = currentPage + 1;
      setCurrentPage(nextPage);
      fetchProducts(nextPage);
    }
  };

  return (
    <View style={styles.container}>
      <FlatList
        ref={flatListRef}
        data={products}
        numColumns={2}
        renderItem={renderProduct}
        keyExtractor={item => item.id.toString()}
        contentContainerStyle={styles.flatListContent}
        ListEmptyComponent={EmptyListComponent}
        refreshing={isRefreshing}
        onRefresh={onRefresh}
        onEndReached={onEndReached}
        onEndReachedThreshold={0.1}
      />
      <Toast />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f6f6f6',
  },
  flatListContent: {
    paddingBottom: 90,
  },
  productContainer: {
    width: '45%',
    marginTop: 10,
    marginHorizontal: 10,
    backgroundColor: '#fff',
    borderRadius: 10,
  },
  productImage: {
    height: 130,
    width: 130,
    alignSelf: 'center',
    marginTop: 20,
  },
  nameStyle: {
    fontWeight: '500',
    fontSize: normalize(14),
    color: '#191919',
    marginTop: 20,
    marginHorizontal: 12,
  },
  emptyListContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: screenHeight / 3,
  },
  emptyListText: {
    fontSize: normalize(16),
    color: '#999',
  },
  pointBgStyle: {
    justifyContent: 'center',
    alignSelf: 'flex-start', // 让 View 的宽度根据内容自动调整
    paddingHorizontal: 8, // 可选：添加内边距使内容与边框有一定间距
    height: 22,
    borderRadius: 11, // 可选：添加圆角效果
    marginTop: 10,
    marginBottom: 20,
    marginLeft: 10,
    backgroundColor: 'rgba(255, 233, 199, 0.5)',
  },
  pointStyle: {
    color: '#F5AF3F',
    fontSize: normalize(12),
  }
});

export default WholesaleScreen;
